package pl.uz.zgora.plan;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.SQLException;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;

public class NotifyService extends Service {
	private PlanUzDataSource ds = null;
	private Timer updatingTimer = null;
	
	final private static SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
	final private static int NOTIFY_ID = 2;
	
	private static int NOTIFY_DELAY = 20; // Czas w minutach do następnych zajęć
	private static CharSequence contentTitle = null;
	private static CharSequence contentText = null;
	private static CharSequence tickerText = null;
	private static NotificationManager mNotificationManager = null;
	private static Notification mNotification = null;
	private static PendingIntent contentIntent = null;
	private static Intent mainMenuIntent = null;
	private static boolean isServiceRunning = false;
	
	public static boolean getServiceState() {
		return isServiceRunning;
	}
	
    private TimerTask notify = new TimerTask() {
    	
        @Override
        public void run() {    
        	Log.d("notify_service", "notify check");
            Przedmiot przedmiot = null;
            
            try {
            	
				przedmiot = ds.getNextTodayClass();
				final Date classStartTime = parser.parse(przedmiot.getGodzinaRozpoczecia());
				int minutes = differenceInMinutes(classStartTime);

				if(minutes <= NOTIFY_DELAY) {
					notifyAboutClass(przedmiot.getNazwa(), minutes);
				}
				
			} catch (SQLException e) {
				showErrorNotification(contentIntent, NotifyService.this, e.getMessage());
			} catch (ParseException e) {
				showErrorNotification(contentIntent, NotifyService.this, e.getMessage());
			} catch (IOException e) {
				showErrorNotification(contentIntent, NotifyService.this, e.getMessage());
			} catch (XmlPullParserException e) {
				showErrorNotification(contentIntent, NotifyService.this, e.getMessage());
			}
        }
    };
    
    private void showErrorNotification(PendingIntent contentIntent,
			Context context, final String msg) {
		contentText = msg;
		mNotification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		mNotificationManager.notify(NOTIFY_ID, mNotification);
	}
    
    public static void setNotifyDelay(final int notifyDelay) {
    	NOTIFY_DELAY = notifyDelay;
	}
	
    private void notifyAboutClass(final String className, int minutesToClass) {
    	tickerText = "Plan UZ";
    	contentTitle = "Następne zajęcia za " + String.valueOf(minutesToClass) +  " min.";
		contentText = className;
    	
    	mNotificationManager = (NotificationManager) getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
		
		int icon = R.drawable.ic_launcher;
		
		long when = System.currentTimeMillis();

		mNotification = new Notification(icon, tickerText, when);
		
		mNotification.setLatestEventInfo(getBaseContext(), contentTitle, contentText, contentIntent);

		mNotificationManager.notify(NOTIFY_ID, mNotification);

		Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
		if(r != null) {
			r.play();
		}
    }
    
    private int differenceInMinutes(Date classStartTime)
    {
    	Calendar calendar = Calendar.getInstance();
    	final Integer currentHour = calendar.get(Calendar.HOUR_OF_DAY);
		final Integer currentMinute = calendar.get(Calendar.MINUTE);
		int minutes = 60 * (classStartTime.getHours() - currentHour);
		minutes += classStartTime.getMinutes() - currentMinute;
		return minutes;
    }
	
	@Override
	public IBinder onBind(Intent intent) { return null; }

	@Override
	public void onDestroy() {
		updatingTimer.cancel();
		Log.d("notify_service", "onDestroy()");
		super.onDestroy();
	}
	
	@Override
    public void onCreate() {
        super.onCreate();
        updatingTimer = new Timer();
        Log.d("notify_service", "onCreate()");
	}
	
	@Override
    public void onStart(Intent intent, int startId) {
		 super.onStart(intent, startId);
		 ds = new PlanUzDataSource(this);
		 mainMenuIntent = new Intent(this, MainMenuActivity.class);
		 contentIntent = PendingIntent.getActivity(this, 0, mainMenuIntent, 0);
		 updatingTimer.scheduleAtFixedRate(notify, 1*60*1000, 5*60*1000);
		 Log.d("notify_service", "onStart()");
	}
}
